package com.sdap2.controller;

import com.sdap2.common.exception.BusinessException;
import com.sdap2.common.model.ApiResult;
import com.sdap2.dto.DeviceDataRequest;
import com.sdap2.dto.DeviceDataResponse;
import com.sdap2.dto.SoilDataStatsDTO;
import com.sdap2.entity.Device;
import com.sdap2.entity.SoilData;
import com.sdap2.entity.enums.DeviceType;
import com.sdap2.service.DeviceDataService;
import com.sdap2.service.DeviceService;
import com.sdap2.service.SoilDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Tag(name = "设备数据")
@RestController
@RequestMapping("/api/device-data")
@RequiredArgsConstructor
public class DeviceDataController {
    
    private static final Logger log = LoggerFactory.getLogger(DeviceDataController.class);
    
    private final DeviceDataService deviceDataService;
    private final SoilDataService soilDataService;
    private final DeviceService deviceService;
    
    @Operation(summary = "获取设备数据")
    @PostMapping("/greenhouse/{greenhouseId}")
    public ApiResult<List<DeviceDataResponse>> getDeviceData(
            @Parameter(description = "大棚ID") @PathVariable Long greenhouseId,
            @Parameter(description = "设备序列号列表") @RequestBody List<String> deviceIds,
            @Parameter(description = "认证token") @RequestHeader("Authorization") String token) {
        // 获取设备实时数据
        List<DeviceDataResponse> data = deviceDataService.getDeviceData(greenhouseId, deviceIds, token);
        
        // 保存每个设备的每条数据记录
        for (DeviceDataResponse deviceData : data) {
            String serialNumber = deviceData.getBoxId();
            log.info("Processing device data with serialNumber: {}", serialNumber);
            
            try {
                // 获取设备信息
                Device device = deviceService.getDeviceBySerialNumber(serialNumber)
                    .orElseThrow(() -> new BusinessException("设备不存在: " + serialNumber));
                    
                // 根据设备类型保存数据
                if (DeviceType.SOIL_MOISTURE.equals(device.getDeviceType()) ||
                    DeviceType.SOIL_TEMPERATURE.equals(device.getDeviceType())) {
                    // 创建新的土壤数据记录
                    SoilData soilData = new SoilData();
                    soilData.setName(deviceData.getName());
                    soilData.setValue(BigDecimal.valueOf(deviceData.getValue()));
                    soilData.setUnit(device.getUnit());
                    soilData.setDevice(device);
                    
                    // 保存这条记录
                    soilDataService.save(soilData);
                    log.info("Saved soil data for device: {}, value: {}", serialNumber, deviceData.getValue());
                }
            } catch (Exception e) {
                // 记录错误但继续处理其他设备数据
                log.error("Error processing device data for serialNumber: " + serialNumber, e);
            }
        }
        
        return ApiResult.success(data);
    }
    
    @Operation(summary = "获取土壤设备数据统计")
    @GetMapping("/soil/{serialNumber}/stats")
    public ApiResult<List<SoilData>> getSoilDataStats(
            @Parameter(description = "设备序列号") @PathVariable String serialNumber,
            @Parameter(description = "认证token") @RequestHeader("Authorization") String token) {
        return ApiResult.success(soilDataService.getDataStats(serialNumber, token));
    }
} 